<?php
declare (strict_types = 1);

namespace app\store\controller;

use app\store\model\AppointmentForm as AppointmentFormModel;
use app\store\model\User as UserModel;
use app\store\service\order\Export as ExportService;
use app\common\enum\FormStatus as FormStatusEnum;

class Appointment extends Controller
{
    public function list()
    {
        $model = new AppointmentFormModel;
        $list = $model->getList($this->request->param());
        return $this->renderSuccess(compact('list'));
    }

    public function detail(int $appointmentId)
    {
        $form = AppointmentFormModel::get($appointmentId);
        return $this->renderSuccess(compact('form'));
    }

    public function add()
    {
        // 新增记录
        $model = new AppointmentFormModel;
        $userId = $this->postForm()['user_id'];
        $user = UserModel::get($userId);
        if ($model->add($user->nick_name, $this->postForm())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    public function edit(int $appointmentId)
    {
        $model = AppointmentFormModel::get($appointmentId);
        // 更新记录
        $userId = $this->postForm()['user_id'];
        $user = UserModel::get($userId);
        if ($model->edit($user->nick_name, $this->postForm())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    public function delete(int $appointmentId)
    {
        $model = AppointmentFormModel::get($appointmentId);
        if (!$model->remove($appointmentId)) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     * 导出数据
     */
    public function export()
    {

        $service = new ExportService;
        if (!$downloadPath = $service->exportAppointment($this->request->param())) {
            $this->renderError($service->getError() ?: '导出失败');
        }
        return $this->renderSuccess(compact('downloadPath'));
    }

    // 切换表单状态
    public function status(int $appointmentId)
    {
        $model = AppointmentFormModel::get($appointmentId);
        if (!$model->switchStatus(FormStatusEnum::PROCESSED)) {
            return $this->renderError($model->getError() ?: '修改失败');
        }
        return $this->renderSuccess('已修改状态为：已处理');
    }
}
